package com.rtsapp.server.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import com.rtsapp.server.logger.Logger;

public class FtpUtils {

	private static final Logger log =com.rtsapp.server.logger.LoggerFactory.getLogger(FtpUtils.class);

	public static Map<String, String> download(String ipAddress,
			String username, String password, String remotePath,
			String localPath) {

		Map<String, String> map = new HashMap<String, String>();

		FTPClient ftp = new FTPClient();

		FileOutputStream fos = null;

		try {

			ftp.connect(ipAddress);

			ftp.login(username, password);

			fos = new FileOutputStream(remotePath);

			ftp.setBufferSize(1024);

			// 设置文件类型（二进制）

			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

			ftp.retrieveFile(remotePath, fos);

			downloadFiles(ftp, remotePath, localPath, map);

		} catch (IOException e) {

			e.printStackTrace();

			throw new RuntimeException("FTP客户端出错！", e);

		} finally {

			try {

				if (fos != null)

					fos.close();

			} catch (IOException e1) {

				e1.printStackTrace();

			}

			try {

				ftp.disconnect();

			} catch (IOException e) {

				e.printStackTrace();

				throw new RuntimeException("关闭FTP连接发生异常！", e);

			}

		}

		return map;

	}

	/************************************
	 * 
	 * 下载远程目录
	 * 
	 * */

	private static void downloadFiles(FTPClient ftp, String remoteFileName,
			String localPath, Map<String, String> map) throws IOException {

		// 转移到FTP服务器目录

		ftp.changeWorkingDirectory(remoteFileName);

		FTPFile[] fs = ftp.listFiles();

		for (FTPFile ff : fs) {

			if (ff.isDirectory()) {

				downloadFiles(ftp, remoteFileName + "/" + ff.getName(),
						localPath + "/" + ff.getName(), map);

			} else {

				File localFile = new File(localPath + "/" + ff.getName());

				if (!localFile.getParentFile().exists()) {

					localFile.getParentFile().mkdirs();

				}

				OutputStream is = new FileOutputStream(localFile);

				ftp.retrieveFile(ff.getName(), is);

				map.put(ff.getName(), ff.getSize() + ""); // 放数据

				log.info("ftp下载远程文件：" + remoteFileName + "/" + ff.getName()
						+ "(字节数：" + ff.getSize() + ")" + "到" + localPath + "/"
						+ ff.getName());

				is.close();

			}

		}

	}

	public static void main(String[] args) {
		download("123.59.55.34", "yuanyoures", "yuanyouresfile", "debug/", "/Users/admin/Applications/");
	}
}